﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ZLB_Unility.Common
{
    public class MD5Utils
    {
        /**//// <summary>
            /// MD5 16位加密 加密后密码为小写
            /// </summary>
            /// <param name="ConvertString"></param>
            /// <returns></returns>
        public static string Md5To16(string ConvertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
            t2 = t2.Replace("-", "");
            t2 = t2.ToLower();
            return t2;
        }

        /**//// <summary>
            /// MD5　32位加密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
        public static string Md5To32(string str, string chat = "utf-8")
        {
            byte[] bys = Encoding.GetEncoding(chat).GetBytes(str);
            return MD5ConvertTo32(bys);
        }

        public static string Md5To32(byte[] bys)
        {
            return MD5ConvertTo32(bys);
        }

        public static string CreateMD5(byte[] bys)
        {
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(bys);
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为大写
            return sb.ToString().ToUpper();
        }


        public static string CreateMD5(string str)
        {
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为大写
            return sb.ToString().ToUpper();
        }

        private static string MD5ConvertTo32(byte[] bys)
        {
            MD5 md5 = MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] bs = md5.ComputeHash(bys);
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
